package javawdw.util;

/**
 * 连接器
 * 
 * @author wangdawei
 * 
 */
public class Joiner {
	private char connector;

	/**
	 * 以connector作为连接符将数组array连接起来
	 * 
	 * @param array
	 *            给定数组
	 * @param connector
	 *            给定连接符
	 * @return 返回连接结果
	 */
	public static <E> String join(E[] array, char connector) {
		Joiner joiner = new Joiner(connector);
		return joiner.join(array);
	}

	/**
	 * 以给定的连接符构造连接器
	 * 
	 * @param connector
	 */
	public Joiner(char connector) {
		this.connector = connector;
	}

	/**
	 * 使用当前连接器连接给定数组
	 * 
	 * @param array
	 *            给定数组
	 * @return 返回连接结果
	 */
	public <E> String join(E[] array) {
		if (array == null)
			return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < array.length; i++) {
			sb.append(array[i]);
			sb.append(i < array.length - 1 ? connector : "");
		}
		return sb.toString();
	}
}